import 'package:flutter/material.dart';

import '../entity/palette_model.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';

import '../services/palette_service.dart';
import '../widgets/toast.dart';

class SketchpadColorSetting extends StatefulWidget {
  final PaletteModel paletteModel;

  const SketchpadColorSetting({super.key, required this.paletteModel});

  @override
  State<SketchpadColorSetting> createState() => _SketchpadColorSettingState();
}

class _SketchpadColorSettingState extends State<SketchpadColorSetting> {
  late PaletteModel paletteModel;
  bool isEdit = false, deleteCheck = true;

  @override
  void initState() {
    paletteModel = widget.paletteModel;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    final bottomInset = MediaQuery.of(context).viewInsets.bottom;
    bool isLink = paletteModel.id != null && paletteModel.id != 0;
    // 包含安全区域的尺寸
    double safeWidth = mediaQuery.size.width,
        safeHeight =
            mediaQuery.size.height -
            mediaQuery.padding.top -
            mediaQuery.padding.bottom -
            (bottomInset > 0 ? (bottomInset + 30) : 0);
    double buttonHeight = 60,
        buttonSpace = 2,
        listViewHeight =
            safeHeight -
            ((buttonHeight + buttonSpace) * (isLink ? 2 : 1)) -
            kToolbarHeight;
    ButtonStyle buttonStyle = TextButton.styleFrom(
      fixedSize: Size(safeWidth, buttonHeight), // 设置固定尺寸
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.zero, // 设置为矩形
      ),
    );
    List<Widget> childrenList = [
      TextButton(
        onPressed: () {
          _showPaletteSelectorDialog(context);
        },
        style: buttonStyle,
        child: Text('切换调色板[${isLink ? paletteModel.name : '非绑定'}]'),
      ),
      SizedBox(height: buttonSpace),
      SizedBox(
        height: listViewHeight,
        child: ListView(
          children: (paletteModel.data.isEmpty
              ? [
                  ListTile(
                    title: Text('无颜色'),
                    subtitle: Text('无颜色'),
                    onTap: () {},
                  ),
                ]
              : [
                  for (var colorItem in paletteModel.data)
                    Container(
                      color: colorItem.color,
                      child: ListTile(
                        title: Text(
                          colorItem.name,
                          style: TextStyle(
                            color: useWhiteForeground(colorItem.color)
                                ? Colors.white
                                : Colors.black,
                          ),
                        ),
                        subtitle: Text(
                          colorItem.description,
                          style: TextStyle(
                            color: useWhiteForeground(colorItem.color)
                                ? Colors.white
                                : Colors.black,
                          ),
                        ),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: Icon(
                                Icons.edit,
                                color: useWhiteForeground(colorItem.color)
                                    ? Colors.white
                                    : Colors.black,
                              ),
                              onPressed: () {
                                _showEditPaletteColorDialog(
                                  context,
                                  colorItem,
                                  false,
                                );
                              },
                            ),
                            // SizedBox(width: 10),
                            IconButton(
                              icon: Icon(
                                colorItem.view
                                    ? Icons.visibility
                                    : Icons.visibility_off,
                                color: useWhiteForeground(colorItem.color)
                                    ? Colors.white
                                    : Colors.black,
                              ),
                              onPressed: () {
                                setState(() {
                                  colorItem.view = !colorItem.view;
                                });
                                isEdit = true;
                              },
                            ),
                            // SizedBox(width: 10),
                            IconButton(
                              icon: Icon(
                                Icons.delete,
                                color: useWhiteForeground(colorItem.color)
                                    ? Colors.white
                                    : Colors.black,
                              ),
                              onPressed: () {
                                if (deleteCheck) {
                                  _showDeleteColorDialog(context, colorItem);
                                } else {
                                  setState(() {
                                    paletteModel.data.remove(colorItem);
                                  });
                                }
                              },
                            ),
                            // SizedBox(width: 10),
                          ],
                        ),
                      ),
                    ),
                ]),
        ),
      ),
    ];
    if (isLink) {
      childrenList.insert(
        1,
        TextButton(
          onPressed: () {
            _showUnlinkPaletteDialog(context);
          },
          style: buttonStyle,
          child: Text('断开调色板绑定'),
        ),
      );
      childrenList.insert(1, SizedBox(height: buttonSpace));
    }
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (bool didPop, Object? result) async {
        if (!didPop) {
          Navigator.of(context).pop(isEdit ? paletteModel : null);
        }
      },
      child: Scaffold(
        appBar: AppBar(
          // 设置页标题
          title: const Text("颜色管理"),
          leading: IconButton(
            // 返回按钮
            icon: const Icon(Icons.arrow_back),
            // 返回到上一页
            onPressed: () async {
              Navigator.of(context).pop(isEdit ? paletteModel : null);
            },
          ),
          // 右上角按钮区域
          actions: [
            TextButton.icon(
              // icon: const Icon(Icons.add),
              label: const Text('添加颜色'),
              onPressed: () {
                _showEditPaletteColorDialog(
                  context,
                  ColorItem(
                    name: '',
                    description: '',
                    view: true,
                    color: Colors.cyanAccent,
                  ),
                  true,
                );
              },
            ),
            SizedBox(width: 10),
          ],
        ),
        body: Column(children: childrenList),
      ),
    );
  }

  /// 调色板颜色编辑弹窗
  void _showEditPaletteColorDialog(
    BuildContext context,
    ColorItem colorItem,
    bool insert,
  ) {
    final nameController = TextEditingController(text: colorItem.name),
        descriptionController = TextEditingController(
          text: colorItem.description,
        );

    Color itemColor = colorItem.color;
    bool view = colorItem.view;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return AlertDialog(
              title: Text('${insert ? '新增' : '修改'}颜色'),
              content: SingleChildScrollView(
                child: Column(
                  children: [
                    ColorPicker(
                      pickerColor: itemColor,
                      onColorChanged: (Color color) {
                        // 更新颜色选择器内部状态
                        setState(() {
                          itemColor = color;
                        });
                        // 同时更新外层状态以刷新页面
                        this.setState(() {
                          // 外层状态更新，但不需要额外操作
                        });
                      },
                      colorPickerWidth: 300.0,
                      pickerAreaHeightPercent: 0.7,
                      enableAlpha: true,
                      displayThumbColor: true,
                      labelTypes: [],
                      paletteType: PaletteType.hsv,
                      pickerAreaBorderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(2.0),
                        topRight: Radius.circular(2.0),
                      ),
                      portraitOnly: true,
                    ),
                    SwitchListTile(
                      title: const Text('是否可见'),
                      value: view,
                      onChanged: (bool value) {
                        // 更新Switch内部状态
                        setState(() {
                          view = value;
                        });
                        // 同时更新外层状态
                        this.setState(() {
                          isEdit = true;
                        });
                      },
                    ),
                    TextField(
                      controller: nameController,
                      decoration: const InputDecoration(hintText: "名称(非必填)"),
                    ),
                    TextField(
                      controller: descriptionController,
                      decoration: const InputDecoration(hintText: "备注(非必填)"),
                    ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    for (var item in paletteModel.data) {
                      if (item.color == itemColor && item != colorItem) {
                        var msg = item.name.isEmpty ? '' : "[${item.name}]";
                        Toast.show("该颜色已存在$msg", context);
                        return;
                      }
                    }
                    if (nameController.text.length > 10) {
                      Toast.show("名称最长10个字", this.context);
                      return;
                    }
                    colorItem.color = itemColor;
                    colorItem.view = view;
                    colorItem.name = nameController.text;
                    colorItem.description = descriptionController.text;
                    if (insert) {
                      paletteModel.data.insert(0, colorItem);
                    }
                    this.setState(() {
                      isEdit = true;
                    });
                    Navigator.of(context).pop();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  /// 删除Color弹窗
  void _showDeleteColorDialog(BuildContext context, ColorItem colorItem) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return AlertDialog(
              title: Text('删除此颜色?'),
              content: SingleChildScrollView(
                child: Column(
                  children: [
                    SwitchListTile(
                      title: const Text('退出此页面前不再提醒'),
                      value: !deleteCheck,
                      onChanged: (bool value) {
                        // 更新Switch内部状态
                        setState(() {
                          deleteCheck = !value;
                        });
                      },
                    ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    this.setState(() {
                      paletteModel.data.remove(colorItem);
                    });
                    Navigator.of(context).pop();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  /// 断开调色板绑定确认弹窗
  void _showUnlinkPaletteDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('断开调色板绑定'),
          content: const Text('确定要断开当前调色板的绑定吗？断开后的修改将不会同步到全局的调色板中。'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                setState(() {
                  // 移除绑定ID，使其成为本地调色板
                  paletteModel.id = 0;
                  isEdit = true;
                });
                Navigator.of(context).pop();
                // 重新构建界面以更新按钮显示
                setState(() {});
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  /// 选择调色板弹窗
  void _showPaletteSelectorDialog(BuildContext context) {
    List<PaletteModel> paletteList = []; // 明确指定类型
    PaletteService.queryAll().then((result) {
      setState(() {
        paletteList = result.cast<PaletteModel>(); // 确保类型转换
      });
    });
    showDialog(
      context: context,
      builder: (BuildContext context) {
        MediaQueryData mediaQuery = MediaQuery.of(context);
        // 包含安全区域的尺寸
        double safeWidth = mediaQuery.size.width;
        double iconSize = 25;
        int iconCount = (safeWidth / iconSize).floor() - 7;
        if (iconCount < 0) {
          iconCount = 0;
        }

        List<Widget> childrenList = (paletteList.isEmpty
            ? [
                ListTile(
                  title: Text('无调色板'),
                  subtitle: Text('无调色板'),
                  onTap: () {},
                ),
              ]
            : paletteList
                  .map<Widget>(
                    (PaletteModel pm) => ListTile(
                      title: Text(pm.name),
                      subtitle: Row(
                        children: pm.data
                            .take(iconCount)
                            .map<Widget>(
                              (colorItem) => Icon(
                                colorItem.view
                                    ? Icons.square
                                    : Icons.visibility_off,
                                color: colorItem.color,
                                size: 25,
                              ),
                            )
                            .toList(),
                      ),
                      onTap: () {
                        setState(() {
                          paletteModel = pm;
                          isEdit = true;
                        });
                        Navigator.of(context).pop();
                      },
                    ),
                  )
                  .toList());
        childrenList.insert(
          0,
          Text(
            '在本页面切换调色板之前的修改将不会同步到之前绑定的调色板',
            style: TextStyle(color: Colors.red),
          ),
        );
        return AlertDialog(
          title: const Text('切换调色板'),
          content: Column(children: childrenList),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('取消'),
            ),
          ],
        );
      },
    );
  }
}
